var Session = require('../../vendor/qcloud-weapp-client-sdk/lib/session.js');
var config = require('../../config.js');
var commons = require('../../commons.js');
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');
var register = require('../../template/register/register.js');
var utils = require('../../vendor/qcloud-weapp-client-sdk/lib/utils.js');
var aQp = 0; //定义一个全局变量
var bXz = 0; //定义一个全局变量
var tsay = 0;
const Flutter = require('./flutter-hearts-zmt.js');
let random = {
  uniform: function(min, max) {
    return min + (max - min) * Math.random();
  },
  uniformDiscrete: function(i, j) {
    return i + Math.floor((j - i + 1) * random.uniform(0, 1));
  },
};
let imgs = [{
    url: 'img/1.png',
    width: 40,
    height: 40
  },
  {
    url: 'img/2.png',
    width: 40,
    height: 40
  },
  {
    url: 'img/3.png',
    width: 40,
    height: 40
  },
  {
    url: 'img/4.png',
    width: 40,
    height: 40
  },
  {
    url: 'img/5.png',
    width: 40,
    height: 40
  }
]
var index = {

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    tabList: ["互动", "榜单", "介绍"],
    detailID: "", //接收传过来的直播间id
    detailData: "", //房间的数据
    scrollTop: 0, //判断输入框的位置
    pullbg: false, //判断视频封面图
    HtmlUrlData: "", //浏览器网页地址
    beginHide: false, //判断开始直播按钮是不是有
    // 发送实时聊天
    access_token: '',
    nickname: '',
    avatar_url: '',
    liaoTianid: '',
    canvasShow: false, //二维码分享海报图
    wxHeight: "", //获取小程序的高度
    playBegin: false, //开始播放视频
    userId: '',
    newsList: [], //追加聊天信息
    oldNewList: "", //历史聊天记录
    isOpenData: false,
    dataTimeHtml: '距开始还有:00天00小时00分00秒', //倒计时时间
    timeShow: false, //倒计时显示判断
    time: 15, //
    input: '', //聊天框内容
    wxW: '750rpx',
    orientation: "vertical",
    wxH: '400rpx',
    // 小心心
    style_img: '',
    // 点赞量
    zanNumData: '1002455',
    zanNumtext:"1002455",
    // 观看量
    countNum: ""

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var wxH = wx.getSystemInfoSync().windowHeight;
    this.setData({
      detailID: options.detailID,
    })
    this.flutter = new Flutter({
      width: 170,
      height: 300
    }, 'canvas');

  },
  // 关闭海报
  clickClostCanvas(){
    this.setData({
      canvasShow: false
    })
  },
  // 选择分享
  clickXz() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '发送给好友',
      cancelText: "分享好友",
      confirmText: "发朋友圈",
      success(res) {
        if (res.confirm) {
          utils.showLoading("请稍后")
          that.yaoqi();
        } else if (res.cancel) {
          that.onShareAppMessage();
        }
      }
    })
  },
  // 生成二维码
  yaoqi() {
    var that = this;
    var textSpli = that.data.detailData.info.title;
    if (textSpli.length > 11) {
      textSpli = textSpli.slice(0, 11);
      console.log(textSpli)
    }
    const ctx = wx.createCanvasContext('myCanvas')
    ctx.fillRect(5, 0, 320, 520)
    ctx.drawImage("../../images/fxbg.jpg", 0, 0, 320, 520)
    ctx.drawImage(that.data.avatar_url, 20, 35, 40, 40)
    ctx.drawImage(that.data.detailData.info.thumb, 25, 90, 270, 170)

    ctx.setFillStyle('#ffffff')
    ctx.fillText(that.data.nickname, 197, 50)

    ctx.setFillStyle('#000')
    ctx.setTextAlign('center')
    ctx.setFontSize(20)
    ctx.fillText(textSpli, 150, 320)
    ctx.draw()
    that.setData({
      canvasShow: true
    })
    // 生成页面的二维码
    wx.request({
      // 获取token
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential',
      data: {
        appid: 'wx4d3ac763bb500103',
        secret: 'b181549812e9d8a91edca2d2e08a1b4b'
      },
      success(res) {
        wx.request({
          // 调用接口C
          url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + res.data.access_token,
          method: 'POST',
          data: {
            "path": "pages/meiTuan/meiTuan",
            "width": 430
          },
          success(res) {
            wx.hideLoading();
            // res是二进制流，后台获取后，直接保存为图片，然后将图片返回给前台
            // 后台二进制怎么转图片？我也不会后台，学会了再贴代码
          }
        })
      }
    })


    // ctx.draw(false, function () {
    //   wx.canvasToTempFilePath({
    //     fileType: 'jpg',
    //     canvasId: 'myCanvas',
    //     success: function (res) {
    //       that.setData({
    //         shareSrc: res.tempFilePath
    //       });
    //     },
    //     fail: function () {
    //       wx.showToast({
    //         title: "二维码生成错误",
    //         icon: "none"
    //       });
    //     }
    //   })
    // })
  },
  // 点赞
  shoot() {
    let img = imgs[random.uniformDiscrete(0, imgs.length - 1)];
    this.flutter.bubble(img);
    this.setData({
      zanNumtext: ((Number(this.data.zanNumData) + Number(1)) / 10000).toFixed(2)+"万"
    })
  },
  // 点击全屏播放
  clickQuanPing: function() {
    if (aQp == 0) {
      aQp = 1;
      var wxH = wx.getSystemInfoSync().windowHeight;
      var wxW = wx.getSystemInfoSync().windowWidth;
      this.setData({
        wxW: wxW + "px",
        wxH: wxH + "px",
        orientation: "vertical"
      })
    } else {
      aQp = 0;
      this.setData({
        wxW: '750rpx',
        wxH: '400rpx',
        orientation: "horizontal"
      })
    }

  },
  // 点击旋转
  clickxuanzhuan: function() {
    if (bXz == 0) {
      bXz = 1;
      this.setData({
        orientation: "vertical"
      })
    } else {
      bXz = 0;
      this.setData({
        orientation: "horizontal"
      })
    }

  },
  // 点击开始播放
  clickPlay() {
    var that = this;
    this.ctx.play({
      success: res => {
        console.log('play success');
        that.setData({
          pullbg: true
        })
      },
      fail: res => {
        // console.log('play fail');
        utils.showError('播放失败请重试');
        that.setData({
          pullbg: false
        })
      }
    })
  },
  // 历史浏览请求
  indexListData: function() {
    var that = this;
    qcloud.request({
      login: true,
      url: config.service.historyAddUrl,
      data: {
        room_id: this.data.detailID
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {

      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {

      }
    });

  },
  // 历史聊天记录请求
  roomcommonUrl: function() {
    var that = this;
    qcloud.request({
      login: true,
      url: config.service.roomcommonUrl,
      data: {
        id: this.data.detailID
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        that.setData({
          oldNewList: res.data.data
        })
        that.demoHeight();
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {
        setTimeout(function () {
          wx.hideLoading();
          wx.stopPullDownRefresh();
        },1000)
      }
    });

  },
  // 开始直播
  subAddZhiBo: function() {
    var pushurl = this.data.detailData.info.pushurl;
    var self = this;
    wx.setClipboardData({
      data: pushurl,
      success: function(res) {
        // self.setData({copyTip:true}),
        utils.showError("复制成功");
        setTimeout(function() {
          wx.navigateTo({
            url: '../push/index?pushurl=' + pushurl,
          })
        }, 500)
      }
    });

  },
  // 复制粘贴
  copyHtmlUrl: function(e) {
    var self = this;
    wx.setClipboardData({
      data: self.data.HtmlUrlData,
      success: function(res) {
        // self.setData({copyTip:true}),
        utils.showError("复制成功");
      }
    });
  },
  // 检测推流状态
  statechange(e) {
    console.log('live-player code:', e.detail.code);
    var that = this;
    if ([-2302, -2301, 3001, 3002, 3003, 3005].indexOf(+e.detail.code) !== -1) {
      setTimeout(function() {
        that.setData({
          pullbg: false,
          timeShow: true
        })
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '播放失败' + e.detail.code
        })
      }, 500)
    } else {
      console.log("开始直播:" + e.detail.code)
      that.setData({
        pullbg: true,
        timeShow: false
      })
    }
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg)
    setTimeout(function() {
      wx.showToast({
        image: '/res/img/err_icon.png',
        title: '播放失败'
      })
    }, 800)
  },

  // 选项卡切换
  clickTab: function(e) {
    var id = e.currentTarget.id;
    if (id == 1) {
      wx.navigateTo({
        url: '../Ranking/Ranking?detailID=' + this.data.detailID,
      })
    } else {
      this.setData({
        currentTab: id
      })
    }

  },
  // 点击关注
  clickGuanZhu: function() {
    // 关注直播传的是id 不是uierid
    // type_id 0 是 直播间  type_id 1 关注是个人
    var room_id = this.data.detailData.info.id;
    var that = this;
    qcloud.request({
      login: false,
      url: config.service.collAddUrl,
      data: {
        type_id: 1,
        room_id: room_id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        utils.showError(res.data.data.msg);
        that.detailsQing();
      },
      fail: function(res) {
        utils.showError(res.message)
      },
      complete: function() {
        
      }
    });
  },
  // 点击关注个人主播
  clickGuanZhuZhu: function() {
    // 关注直播传的是id 不是uierid
    // type_id 0 是 直播间  type_id 1 关注是个人
    var room_id = this.data.detailData.info.userId;
    var that = this;
    qcloud.request({
      login: false,
      url: config.service.collAddUrl,
      data: {
        type_id: 0,
        room_id: room_id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        utils.showError(res.data.data.msg);
        that.detailsQing();
      },
      fail: function(res) {
        utils.showError(res.message)
      },
      complete: function() {
       
      }
    });
  },
  demoHeight: function() {
    var that = this;
    //创建节点选择器
    var query = wx.createSelectorQuery();
    //选择id
    query.select('#wizhiDemo').boundingClientRect()
    query.exec(function(res) {
      // console.log('打印demo的元素的信息', res);
      // console.log('打印高度', res[0].height);
      if (res[0].height > 320) {
        that.setData({
          scrollTop: res[0].height
        })
      }
    })
  },
  // 请求房间详情
  detailsQing: function() {
    var that = this;
    utils.showLoading();
    qcloud.request({
      login: true,
      url: config.service.liveDetailsUrl,
      data: {
        id: that.data.detailID
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.data.data.info.userId == that.data.userId) {
          that.setData({
            beginHide: true
          })
        }
        that.setData({
          detailData: res.data.data,
          countNum: commons.dateTools.wanNumZh(res.data.data.info.click)
        })
        // 获取直播倒计时
        that.show_time(res.data.data.info.stime * 1000);
        // 设置标题
        wx.setNavigationBarTitle({
          title: res.data.data.info.title
        });
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {
       
      }
    });
  },
  // 倒计时
  show_time: function(time_endS) {
    var that = this;
    setTimeout(function() {
      that.setData({
        timeShow: true
      })
    }, 1000)
    var time_end = time_endS;
    var int_day, int_hour, int_minute, int_second;
    var timerID = setInterval(function() {
      // 获取当前时间
      var time_now = new Date().getTime();
      // 结束时间减去当前时间
      var time_distance = time_end - time_now;
      if (time_distance >= 0) {
        // 天时分秒换算
        int_day = Math.floor(time_distance / 86400000)
        time_distance -= int_day * 86400000;
        int_hour = Math.floor(time_distance / 3600000)
        time_distance -= int_hour * 3600000;
        int_minute = Math.floor(time_distance / 60000)
        time_distance -= int_minute * 60000;
        int_second = Math.floor(time_distance / 1000)
        // 天时分秒为单数时、前面加零站位
        if (int_day < 10)
          int_day = "0" + int_day;
        if (int_hour < 10)
          int_hour = "0" + int_hour;
        if (int_minute < 10)
          int_minute = "0" + int_minute;
        if (int_second < 10)
          int_second = "0" + int_second;

        // 显示时间
        var timeHtml = "距开始还有:" + int_day + "天" + int_hour + "小时" + int_minute + "分" + int_second + "秒";
        that.setData({
          dataTimeHtml: timeHtml
        })
      } else {
        that.setData({
          timeShow: false,
          dataTimeHtml: "距开始还有:00天00小时00分00秒"
        })
        clearInterval(timerID)
      }
    }, 1000);
  },
  websoket: function() {
    var _this = this;
    //建立连接
    const socket = wx.connectSocket({
      url: "wss://live.xiaochengshi.net/wss",
      method: 'GET',
      success: function() {
        console.log("连接成功...")
      },
      fail: function() {
        console.log("连接失败...")
      }
    })
    // 判断是否断开连接
    wx.onSocketError(function(res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    // 当socket连接打开时，输入用户名id登录
    // 建立连接
    wx.onSocketOpen((res) => {
      var login_data = {
        "type": "login",
        "client_name": this.data.nickname,
        "userId": this.data.liaoTianid,
        "room_id": this.data.detailID,
        "avatar_url": this.data.avatar_url
      }
      this.roomcommonUrl();
      console.log("websocket握手成功，发送登录数据:", login_data);
      socket.send({
        data: JSON.stringify(login_data)
      })

    })
    // 监听WebSocket 接受到服务器的消息事件
    wx.onSocketMessage((res) => {
      var list = [];
      list = this.data.newsList;
      var _data = JSON.parse(res.data);
      list.push(_data);
      // console.log('接收的数据:', _data)
      this.setData({
        newsList: list
      });
      this.demoHeight();
    })
  },
  // 发送聊天
  sendFasong: function() {
    var that = this;
    if (this.data.input !== '') {
      if (tsay == 0) {
        tsay = 1;
        var timeNum = setInterval(function() {
          tsay = 0;
          console.log("就执行了一次");
          clearTimeout(timeNum);
        }, 6000);
        var temp = {
          type: 'say',
          userId: that.data.liaoTianid,
          to_client_id: 'all',
          to_client_name: that.data.nickname,
          avatar_url: that.data.avatar_url,
          content: that.data.input
        }
        wx.sendSocketMessage({
          data: JSON.stringify(temp)
        })
        that.setData({
          input: ''
        })
      } else {
        utils.showError("您说话太快了");
      }
    } else {
      utils.showError("请输入发言");
    }
  },
  // 检测滚动条
  scroll: function(e) {
    console.log(e.detail.scrollHeight)
    this.setData({
      scrollTop: e.detail.scrollHeight
    })
  },
  // 获取内容
  bindChange: function(res) {
    this.setData({
      input: res.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      currentTab: 0
    })
    var that = this;
    var wxH = wx.getSystemInfoSync().windowHeight;
    that.ctx = wx.createLivePlayerContext('player')
    // 获取网页的地址
    var HtmlUrl = config.service.HtmlUrl + "?id=" + this.data.detailID;
    console.log("浏览器网址:" + HtmlUrl);
    qcloud.request({
      login: true,
      url: config.service.isOpenUrl,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.data.data.fieldValue == '1') {
          that.setData({
            isOpenData: false
          })
        } else {
          that.setData({
            isOpenData: true
          })
        }
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {
        that.detailsQing();
        that.indexListData();
        that.websoket();
        that.setData({
          wxHeight: wxH - 283,
          detailID: that.data.detailID,
          HtmlUrlData: HtmlUrl,
          access_token: Session.get().userInfo.access_token,
          nickname: Session.get().userInfo.nickname,
          avatar_url: Session.get().userInfo.avatar_url,
          liaoTianid: Session.get().userInfo.id,
          userId: Session.get().userInfo.id,
        })
        console.log("token:" + Session.get().access_token)
      }
    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.closeSocket()
    console.log('退出房间1')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.closeSocket()
    console.log('退出房间2');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this;
    this.lives();
    return {
      title: this.data.detailData.info.title,
      path: '/pages/details/details?detailID=' + this.data.detailData.info.id,
      imageUrl: this.data.detailData.info.thumb,
      success: function() {
        utils.showSuccess("转发成功");
      }

    };
  },
  lives: function() {
    qcloud.request({
      login: false,
      url: config.service.livesUrl,
      data: {
        room_id: this.data.detailID
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log("分享统计+1")
      },
      fail: function(res) {
        utils.showError(res.message)
      },
      complete: function() {

      }
    });
  }
};
var data = Object.assign(index.data, register.data);
var page = Object.assign(index, register);
page.data = data;
Page(page);